/*
 * iVprog/Alice
 * @description Used to initiate/stop or pause/resume a Thread in 'edu.cmu.cs.stage3.alice.authoringtool.AuthoringTool'
 * @see edu/cmu/cs/stage3/alice/authoringtool/AuthoringTool.java
 */

package edu.cmu.cs.stage3.alice.core.clock;

public class DefaultClock implements edu.cmu.cs.stage3.alice.core.Clock {

 private edu.cmu.cs.stage3.alice.core.World m_world;
 private double m_time;
 private long m_whenPrev;
 private int m_pauseCount;

 public edu.cmu.cs.stage3.alice.core.World getWorld () {
  return m_world;
  }
 public void setWorld (edu.cmu.cs.stage3.alice.core.World world) {
  m_world = world;
  }

 public void start () {
  m_pauseCount = 0;
  m_whenPrev = System.currentTimeMillis();
  if (m_world != null) {
   m_world.start();
   }
  }
 public void stop () {
  m_pauseCount = 0;
  m_whenPrev = -1;
  if (m_world != null) {
   m_world.stop();
   }
  }
 public void pause () {
  m_pauseCount++;
  }
 public void resume () {
  m_pauseCount--;
  if( m_pauseCount == 0 ) {
   m_whenPrev = System.currentTimeMillis();
   }
  }

 private void updateTime () {
  long whenCurr = System.currentTimeMillis();
  long whenDelta = whenCurr - m_whenPrev;
  if (whenDelta > 0) {
   double dt = whenDelta * 0.001;
   m_time += dt;
   }
  m_whenPrev = whenCurr;
  }

 public double getTime () {
  return m_time;
  }

 public double getTimeElapsed () {
  return getTime();
  }

 // To execute instructions
 // From: edu/cmu/cs/stage3/alice/authoringtool/AuthoringTool.java:  worldScheduleRunnable = new Runnable(): void run (): worldClock.schedule() de 'edu.cmu.cs.stage3.alice.core.clock.DefaultClock.schedule()'
 // To  : edu.cmu.cs.stage3.alice.core.World.schedule(World.java:172)
 public void schedule () {
  if (m_pauseCount == 0) {
   if (m_world != null) {
    updateTime();
    m_world.schedule(); // to execute instructions
    }
   }
  }

 }

